package com.zzyl.service.impl;

import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WechatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;




/**
 * @Description MemberServiceImpl
 * @Author Lwj
 * @Date 2024-08-30-20:29
 */
@Service
@Slf4j
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    static List<String> DEFAULT_NICKNAME_PREFIX = Arrays.asList(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );


    /**
     * 小程序端登录登录
     *
     * @param userLoginRequestDto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //1.远程调用接口获取openid
        String openId = wechatService.getOpenId(userLoginRequestDto.getCode());
        //2.根据openid查询数据库member用户
        Member member = memberMapper.getByOpenId(openId);
        //3.判断member用户是否为空(根据判断是否有openid)
        if (ObjectUtil.isEmpty(member)) {
            //3.1 为空，创建Member对象封装openid
            /*member = new Member();
            member.setOpenId(openId);*/
            //创建对象优化模式：建造者设计模式
            member = Member.builder().openId(openId).build();
        }
        //4.远程调用接口获取手机号
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());
        //5.判断用户是否注册过（member的id是否为空）
        if (member.getId() != null) {
            //5.1 如果注册过，判断手机号是否一致，不一致更新数据库
            if (!member.getPhone().equals(phone)) {
                member.setPhone(phone);
                memberMapper.update(member);
            }
        }
        //5.2 没有注册，新增操作
        if (member.getId() == null) {
            //5.2.1 封装手机号到member
            member.setPhone(phone);
            //5.2.2随机生成一个昵称+手机号后4为
            String nickName = DEFAULT_NICKNAME_PREFIX.get((int)Math.random() * DEFAULT_NICKNAME_PREFIX.size()) + phone.substring(7 );
            log.info("昵称{}", nickName);
            member.setName(nickName);
            //5.2.3执行数据库操作
            memberMapper.save(member);
        }
        //6.封装LoginVo返回
        LoginVo loginVo = new LoginVo();
        //6.1 封装nickName
        loginVo.setNickName(member.getName());
        //6.2 封装token
        //首先要定义载荷
        HashMap<String, Object> map = new HashMap<>();
        map.put(Constants.JWT_USERID, member.getId());
        map.put(Constants.JWT_USERNAME, member.getName());
        //生成JWP令牌
        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(), map);
        loginVo.setToken(token);
        //7.返回
        return loginVo;
    }
}
